package com.springboot.thymeleaf.springbootthymeleaf.util;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * @Classname ${小柯}
 * @Description TODO
 * @Date 2019/10/15 21:51
 * @Created by Administrator
 * 防止外部XML注入
 */

@Slf4j
public class XmlCommonUtil {


    public static DocumentBuilder newDocumentBuilderInstance(){
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder safeBuilder = null;
        String feature = null;

        try {
            feature = "http://apache.org/xml/features/disallow-doctype-decl";
            dbf.setFeature(feature, true);

            safeBuilder = dbf.newDocumentBuilder();
        }catch (Exception e){
            log.info("异常" + e + "失败" + feature);
        }
    return safeBuilder;


    }


/*    *//**
     * 由于DocumentHlper.parseText() 无法进行攻击防御设置，故copy一份到此方法中
     *//*
    public static org.dom4j.Document parseText(String text) throws DocumentException{
        org.dom4j.Document result = null;
        SAXReader reader = XmlCommonUtil.newSAReader();
        String encoding = getEncoding(text);

    }

    private static String getEncoding(String text) {


    }*/

    /**
     * 获取安全的SAXReader对象，防止外部实体攻击
     */
    public static SAXReader newSAReader(){
        SAXReader saxReader = null;

        try {
            saxReader = new SAXReader();
            saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        } catch (SAXException e) {
            e.printStackTrace();
            log.info("a doctype was passed into the xml document");
            return null;
        }
        return saxReader;

    }


}
